package com.express.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.express.dto.AddressDto;
import com.express.entity.Address;
import com.express.entity.User;
import com.express.exception.BusinessException;
import com.express.exception.UnauthorizedException;
import com.express.mapper.AddressesMapper;
import com.express.mapper.UserMapper;
import com.express.service.IAddressesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.express.utils.BaseContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author
 * @since 2025-01-25
 */
@Service
public class AddressesServiceImpl extends ServiceImpl<AddressesMapper, Address> implements IAddressesService {
    @Autowired
    private AddressesMapper addressesMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 获取当前用户的地址列表（修复版）
     *
     * @return 地址DTO列表，若无数据返回空列表
     */
    @Override
    public List<AddressDto> getAddressList() {
        // 1. 获取当前用户ID并校验
        Long userId = BaseContext.getCurrentId();
        if (userId == null) {
            throw new UnauthorizedException("用户未登录");
        }

        // 2. 查询用户信息并校验
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        // 3. 查询地址列表（关键修正点：查询该用户的所有地址）
        List<Address> addresses = addressesMapper.selectList(
                new QueryWrapper<Address>().eq("user_id", userId)
        );

        // 4. 处理空结果集
        if (CollectionUtils.isEmpty(addresses)) {
            return Collections.emptyList(); // 返回空列表而非null
        }

        // 5. 转换DTO对象
        return addresses.stream().map(address -> {
            AddressDto dto = new AddressDto();
            // 复制地址属性（增加null检查）
            if (address != null) {
                BeanUtils.copyProperties(address, dto);
            }
            // 合并用户信息
            dto.setUserName(user.getUsername());
            dto.setPhoneNumber(user.getPhoneNumber());
            return dto;
        }).collect(Collectors.toList());
    }

    /**
     * 新增地址
     */
    @Override
    @Transactional
    public void addAddress(AddressDto addressDto) {
        Long userId = BaseContext.getCurrentId();
        // 1. 地址数量校验
        Long count = addressesMapper.selectCount(
                new LambdaQueryWrapper<Address>()
                        .eq(Address::getUserId, userId)
        );
        if (count >= 20) {
            throw new BusinessException("地址数量超过上限，最多保存20条");
        }

        // 2. 重复地址校验
        boolean isDuplicate = addressesMapper.exists(
                new LambdaQueryWrapper<Address>()
                        .eq(Address::getUserId, userId)
                        .eq(Address::getAddressDetail, addressDto.getAddressDetail())
                        .eq(Address::getLatitude, addressDto.getLatitude())
                        .eq(Address::getLongitude, addressDto.getLongitude())
        );
        if (isDuplicate) {
            throw new BusinessException("地址信息重复，请勿重复添加");
        }

        // 3. 处理默认地址
        if (Boolean.TRUE.equals(addressDto.getIsDefault())) {
            addressesMapper.update(
                    new Address().setIsDefault(Boolean.valueOf("0")),
                    new LambdaUpdateWrapper<Address>()
                            .eq(Address::getUserId, userId)
                            .eq(Address::getIsDefault, 1)
            );
        }

        // 4.新增地址
        Address address = new Address();
        BeanUtils.copyProperties(addressDto, address);
        address.setUserId(userId);
        addressesMapper.insert(address);
    }

    /**
     * 删除地址
     *
     * @param id
     */
    @Override
    public void deleteAddress(Long id) {
        Long userId = BaseContext.getCurrentId();
        // 1. 查询地址并校验所有权
        Address address = addressesMapper.selectOne(
                new LambdaQueryWrapper<Address>()
                        .eq(Address::getAddressId, id)
                        .eq(Address::getUserId, userId)
        );
        if (address == null) {
            throw new BusinessException("地址不存在或无权操作");
        }
        // 2. 执行删除
        addressesMapper.deleteById(id);
    }

    /**
     * 更新地址
     */
    @Override
    public void updateAddress(AddressDto addressDto) {
        //判断传递的值为空
        if (addressDto == null) {
            throw new BusinessException("值不能为空");
        }
        Address address = new Address();
        BeanUtils.copyProperties(addressDto, address);
        addressesMapper.updateById(address);
    }

    /**
     * 设置默认地址
     */
    @Override
    public void defaultAddress(Long id) {
        Address address = addressesMapper.selectById(id);
        if (address == null) {

        }
    }
}
